
//*System Include*/
#include <string.h>
//*Local Include*/
#include "Config.h"
#include "osa.h"
#include "service/osa_bsem.h"
#include "Generic.h"
#include "Rs485.h"
#include "init.h"


//********OSA PROTOTIPE

void Drv_Rs485(void);
void Governor(void);
void task_keyboard(void);

//*************************************************************************

//****** P R O T O T Y P E S ******************************************************/

// Global variables
static const char txt[] = "123456789";
static char cmd[] = "";
static TxCommPack *tx_commpack;
static RxCommPack *rx_commpack;


_CONFIG2(IESO_OFF & FNOSC_PRIPLL & FCKSM_CSDCMD & OSCIOFNC_ON & POSCMOD_HS & I2C1SEL_PRI)
_CONFIG1(JTAGEN_OFF & GCP_OFF & GWRP_OFF & COE_OFF & ICS_PGx1 & FWDTEN_OFF & WINDIS_OFF);

int main(void) {

	WORD_VAL cAddr;
    CommProt *comprot_p;
    
    init();
    OS_Init();

    OS_CreateTask(4, Drv_Rs485);
    OS_CreateTask(4, Governor);
    OS_CreateTask(4, task_keyboard);

   

    tx_commpack = calloc(1,sizeof(TxCommPack));
	comprot_p		= calloc(1,sizeof(CommProt));
	
	MSB(cAddr) = 0x01; 
	LSB(cAddr) = 0x01;
    
    Rs485Initialise(cAddr, comprot_p);

    OS_Run();
    
    free(tx_commpack);
    free(comprot_p);
}

void Governor(void) {


    OS_CreateQMsg(DRV_rs485_qmsg_rx, DRV_rs485_msg_q_rx, RS_SIZE_OF_MSGQ);
    OS_CreateQMsg(DRV_rs485_qmsg_tx, DRV_rs485_msg_q_tx, RS_SIZE_OF_MSGQ);


    while (1) {
        if (OS_CheckBSem(BS_BUTTON_1_REL)) {
            OS_SetFlag(Rs485Flag, SER_TX);
            tx_commpack->cStart = 0x02; //FIXME ererdt m
            tx_commpack->cCommand = 0xfe;
            tx_commpack->cLenExpected = 9;
            LSB(tx_commpack->cNetAddr) = 0x01;
            MSB(tx_commpack->cNetAddr) = 0x02;
            strcpy(tx_commpack->c485Buf, txt);

            OS_SendQMsg(DRV_rs485_qmsg_tx, (char*) tx_commpack);
            OS_ResetBSem(BS_BUTTON_1_REL);

        }
        OS_Yield();
    }

}
